<template>
  <div class="app-container" v-loading="pageLoading">
    <div>
      <el-row :gutter="20">
        <el-col :span="10">
          <template v-for="(i, t) in deviceTypeOptions">
            <div class="mb-20" :key="t" v-if="devices.filter(x => x.DeviceType == i.key).length">
              <div class="panel-info">
                <div class="panel-title">{{ i.title }}</div>
                <div class="panel-body">
                  <el-tag effect="dark" v-for="(item, index) in devices.filter(x => x.DeviceType == i.key)"
                    :type="item.IsError ? 'danger' : (item.IsConnected ? 'success' : 'info')" @click="deviceClick(item)"
                    class="device-itemTop" :key="index" size='medium'>
                    {{ item.Name }} <span style="display:block">{{ item.Ip }}:{{ item.Port }}</span>
                  </el-tag>
                </div>
              </div>
            </div>
          </template>
        </el-col>
        <el-col :span="14">
          <div v-show="!!currentDevice.Name" class="right-wrap">
            <div class="panel-info">
              <div class="panel-title">{{ currentDevice.Name }} 设备信息</div>
              <div class="panel-body">
                <div class="flex flexW f-i-c"
                  v-if="currentDevice.ViewType == 2 && currentData.data && Object.keys(currentData).length">
                  <el-tag effect="dark" v-for="(item, index) in currentData.data"
                    :type="currentDevice.IsError ? 'danger' : (currentDevice.IsConnected ? 'success' : 'info')"
                    @click="conveyorLineClick(`${currentDevice.Name}_${item}`, item)" class="device-item mb-10"
                    :key="index">
                    {{ item }}
                  </el-tag>
                </div>
                <div v-if="currentDevice.ViewType == 2 && !!currentConveyorLine">
                  <div class="panel-info mr-20" style="width:100%;">
                    <div class="panel-title">
                      {{ currentConveyorLine }}
                    </div>
                    <div class="panel-body" v-if="currentConveyorLineData.length > 0">
                      <div class="row">
                        <div class="item" v-for="(i, t) in currentConveyorLineData" :key="t">
                          <div class="item_key">{{ i.Name }}：</div>
                          <div class="item_value">{{ i.Value }}</div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <template v-if="currentDevice.ViewType == 1 && currentData.data">
                  <div class="row">
                    <div class="item" v-for="(i, t) in currentData.data" :key="t">
                      <div class="item_key">{{ i.Name }}：</div>
                      <div class="item_value">{{ i.Value }}</div>
                    </div>
                  </div>
                </template>
                <template v-if="currentData.ErrList && currentData.ErrList.length">
                  <ul class="ul">
                    <div style="color:#e6a23c;margin-bottom:4px;font-weight:500">警告信息:</div>
                    <li class="li" v-for="(item, index) in currentData.ErrList" :key="index">{{ item }}</li>
                  </ul>
                </template>
                <template v-if="currentData.btn">
                  <el-divider></el-divider>
                  <div class="mt-20 mb-20 text-center">
                    <template v-for="(i, t) in currentData.btn" :key="t">
                      <el-tooltip effect="light" :content="i.Name" placement="bottom">
                        <el-button class="" size="mini" :type="i.Type"
                          @click="taskSendByBtn(currentDevice.Name, i.Name, i.Value, i.IsDetail)">
                          {{ i.Name }}</el-button>
                      </el-tooltip>
                    </template>
                  </div>
                </template>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <status-detail-dialog :isAutoRequest="true" v-model:visible="statusDetailShow"
      :query="statusDetailQuery"></status-detail-dialog>
  </div>
</template>

<script>
import commonMixin from '@/views/_common/mixin'
import statusDetailDialog from './components/statusDetaildialog.vue'
import LabelItem from '@/components/LabelItem'
import _ from 'lodash'

export default {
  mixins: [commonMixin],
  name: 'wcsHome',
  components: {
    statusDetailDialog,
    LabelItem,
  },
  data: function () {
    return {
      name: 'WCS监控',
      wcsUrl: this.$api.wcsUrl,
      devicesTimer: null,
      deviceDataTimer: null,
      deviceTypeOptions: [
        {
          title: '堆垛机',
          key: 1,
        },
        {
          title: '输送线',
          key: 2,
        },
        {
          title: 'RGV',
          key: 8,
        },
        {
          title: '称重',
          key: 6,
        },
        {
          title: '读码器',
          key: 7,
        },
        {
          title: 'AGV',
          key: 11,
        },
        {
          title: '测温设备',
          key: 9,
        }
      ],
      devices: [],
      currentDevice: {},
      currentData: {},
      currentConveyorLine: '',
      formProps: {
        labelWidth: '150px',
        disabled: true,
      },
      currentConveyorLineObj: {
        Name: '输送线名称',
        PosNo: '输送线编码',
        Status: '状态',
        TaskRunStatus: '运行状态',
        ErrorCode: '故障代码',
        Barcode: '条码',
      },
      statusDetailShow: false, //动作状态详情控制器
      conveyorLineList: [], //输送线list
      conveyorLineTimer: null, //输送线list
      currentConveyorLineData: [], //输送线list
      statusDetailQuery: '',
      curtabName: null,
    }
  },
  created() {
    this.startConnect()
  },
  beforeUnmount: function () {
    this.stopRefresh()
  },
  deactivated: function () {
    this.stopRefresh()
  },
  activated: function () {
    this.startConnect()
  },
  mounted() { },
  methods: {
    // 设备按钮
    taskSendByBtn(deviceName, btnName, path, isDetail = false) {
      if (!this.currentDevice.Name) return
      if (isDetail) {
        this.seeTemp()
        return
      }
      this.$confirm(`确认发送${btnName}信号？`).then((r) => {
        if (r != 'confirm') return
        this.pageLoading = true
        this.http.post(this.$api.wcsUrl + path, {
          deviceName,
          posNo: this.curtabName,
        })
          .then((r) => {
            if (r.data) this.$message.success('货物即将移出至' + r.data)
            this.$message.success('操作成功')
          })
          .finally(() => {
            this.pageLoading = false
          })
      })
    },
    wsConnect() {
      this.sendMsg('devices')
      this.devicesTimer = setInterval(() => {
        this.sendMsg('devices')
      }, 5000)
    },
    sendMsg(msg) {
      if (!this.$api.wcsUrl) return
      this.http.get(this.$api.wcsUrl + 'Wcs/Device/GetInfo?msg=' + msg).then((r) => {
        this.msgReceive(r)
      })
    },
    msgReceive(msg) {
      var i = msg.search(/\|/g)
      if (i == -1) return
      var req = msg.substr(0, i)
      var dataStr = msg.substr(i + 1)
      var data = null
      try {
        data = JSON.parse(dataStr)
      } catch (e) {
        return
      }
      if (req == 'devices') {
        this.devices = data || []
      } else {
        if (req.indexOf('_') != -1) {
          if (req == this.currentConveyorLine) {
            this.currentConveyorLineData = _.cloneDeep(data)
          }
        } else if (req == this.currentDevice.Name) {
          this.currentData = data || {}
        }
      }
    },
    // 设备点击
    deviceClick(device) {
      if (device.Name == this.currentDevice.Name) return
      //if (!device.IsConnected) return

      this.curtabName = null

      if (this.conveyorLineTimer) {
        clearInterval(this.conveyorLineTimer)
        this.currentConveyorLineData = {}
        this.conveyorLineTimer = null
      }
      if (this.deviceDataTimer) {
        clearInterval(this.deviceDataTimer)
        this.deviceDataTimer = null
      }

      this.currentDevice = device
      this.currentConveyorLineData = {}
      this.currentData = {}

      if (!!this.currentDevice.Name) {
        this.sendMsg(this.currentDevice.Name)
        this.deviceDataTimer = setInterval(() => {
          this.sendMsg(this.currentDevice.Name)
        }, 3000)
      }
    },
    // 输送线点击
    conveyorLineClick(conveyorLineName, curtabName) {
      if (conveyorLineName == this.currentConveyorLine) return
      this.curtabName = curtabName
      if (this.conveyorLineTimer) {
        clearInterval(this.conveyorLineTimer)
        this.conveyorLineTimer = null
      }
      this.currentConveyorLineData = {}
      this.currentConveyorLine = conveyorLineName
      this.fields = this.fields2
      if (!!this.currentConveyorLine) {
        this.sendMsg(this.currentConveyorLine)
        this.conveyorLineTimer = setInterval(() => {
          this.sendMsg(this.currentConveyorLine)
        }, 2000)
      }
    },
    startConnect() {
      if (this.wcsUrl && !this.devicesTimer) this.wsConnect()
    },
    stopRefresh() {
      if (this.devicesTimer) clearInterval(this.devicesTimer)
      if (this.deviceDataTimer) clearInterval(this.deviceDataTimer)
      if (this.conveyorLineTimer) clearInterval(this.conveyorLineTimer)
    },
    // 查看详情
    seeTemp() {
      this.statusDetailQuery = this.currentDevice.Name
      this.statusDetailShow = true
    },
  },
}
</script>
<style scoped lang="scss">
.device-itemTop {
  // width: 100px;
  height: 50px;
  cursor: pointer;
  font-size: 14px;
  line-height: 30px;
  word-wrap: break-word !important;
  overflow-wrap: break-word !important;
  margin: 0 10px 10px 0 !important;
}

.device-item {
  // width: 100px;
  height: 50px;
  cursor: pointer;
  font-size: 14px;
  line-height: 30px;
  word-wrap: break-word !important;
  overflow-wrap: break-word !important;
  margin: 0 10px 10px 0 !important;
}
.right-wrap {
  position: sticky;
  top:0;
}
.conveyor-line-item {
  width: 100px;
  height: 50px;
  cursor: pointer;
  font-size: 14px;
  line-height: 26px;
}

.panel-body {
  .panel-info {
    display: inline-block;
    width: 350px;
    margin-bottom: 10px;

    .panel-title {
      text-align: center;
    }
  }
}

.row {
  width: 100%;
  margin: 0 auto;

  .item {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-bottom: 8px;

    .item_key {
      text-align: right;
      font-weight: 600;
      font-size: 16px;
      margin-right: 10px;
      flex: 1;
      color: #999999;
    }

    .item_value {
      overflow: auto;
      overflow-wrap: anywhere;
      flex: 2;
      font-size: 16px;
    }
  }
}


.ul {
  position: relative;
  padding: 20px 10px 0;

  .li {
    list-style: none;
    padding: 3px 10px;
    border: 1px solid #e6a23c;
    margin: 0;
    display: inline-block;
    margin-right: 5px;
    margin-bottom: 5px;
    border-radius: 2px;
    color: #e6a23c;
  }

  // &::after {
  //   content: '警告信息：';
  //   position: absolute;
  //   top: 0;
  //   left: 0;
  //   color: #999;
  //   font-weight: 500;
  //   color: #e6a23c;
  //   padding-left: 13px;
  // }
}
</style>
